package com.wang.mall.controller;

import com.wang.mall.bean.Product;
import com.wang.mall.model.R;
import com.wang.mall.service.ProductService;
import com.wang.mall.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    // 判断商品是否有库存
    @PostMapping("/hasStock")
    public R<List<Map<String, Object>>> getProductsHasStock(@RequestBody List<Long> productIds) {
        List<Map<String, Object>> a = productService.getProductsHasStock(productIds);
        return R.ok(a);
    }


    @GetMapping("/getData")
    public R<PageUtils> getData(Integer page, Integer limit, String productName) {
        PageUtils pageUtils = productService.queryPage(page, limit, productName);
        return R.ok(pageUtils);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('product:list')")
    public R<PageUtils> queryPage(Integer page, Integer limit, String productName) {
        PageUtils pageUtils = productService.queryPage(page, limit, productName);
        return R.ok(pageUtils);
    }

    @GetMapping("/info/{id}")
    public R info(@PathVariable Long id) {
        Product product = productService.getInfo(id);
        return R.ok(product);
    }


    @PostMapping("/save")
    @PreAuthorize("hasAuthority('product:save')")
    public R save(@RequestBody Product product) {
        boolean isOK = productService.saveProduct(product);
        return isOK ? R.ok() : R.fail("添加失败");
    }


    @PostMapping("/update")
    @PreAuthorize("hasAuthority('product:update')")
    public R update(@RequestBody Product product) {
        boolean isOK = productService.updateProduct(product);
        return isOK ? R.ok() : R.fail("修改失败");
    }


    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('product:delete')")
    public R delete(@RequestBody List<Long> ids) {
        boolean isOK = productService.delete(ids);
        return isOK ? R.ok() : R.fail("删除失败");
    }

}
